package com.uubx.service.impl;

import com.uubx.mapper.PermissionMapper;
import com.uubx.pojo.Menu;
import com.uubx.pojo.Permission;
import com.uubx.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author wuguojun
 * @Date 2021/1/5 15:14
 * @Version 1.0
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Override
    public List<Menu> findMenuListByUsername(String username) {
        List<Permission> permissions = permissionMapper.findMenuListByUsername(username);
        List<Menu> menus = new ArrayList<Menu>();
        //绑定一级权限
        for (Permission p : permissions) {
            if (p.getParentId() != 0) {
                //如果不是一级权限，直接进入下次循环
                continue;
            }
            //把一级权限设置到集合中
            menus.add(new Menu(p.getId(), p.getUrl(), p.getParentId(),p.getName()));
            //查找一级菜单权限的二级权限
            for (Menu m : menus) {
                //遍历一级菜单权限
                for (Permission permission : permissions) {
                    //如果不是二级菜单直接进入下次循环
                    if (permission.getPermissionLevel() != 2) {
                        continue;
                    }
                    //如果不是二级权限直接进入下次循环 判断当前遍历的权限是否是一级菜单权限的子权限
                    if (p.getParentId() == m.getMenuId()) {

                        //添加对应的子权限
                        Menu child = new Menu(p.getId(), p.getUrl(), p.getParentId(),p.getName());
                        m.getSubMenu().add(child);

                    }
                }
            }
        }
        return menus;
    }

    @Override
    public List<Permission> findPermissionListByUsername(String username) {
        return permissionMapper.findPermissionListByUsername(username);
    }
}
